/**
 * Created by Administrator on 2017/4/16.
 */
!(function ($) {
  var publish = {
    type: $('#publish_type').val(),
    userId: $.fn.cookie('userId'),
    isLogin: $.fn.cookie('isLogin'),
    init: function () {
      this.typeChange()
      this.uploadImg()
      this.getCatData(this.type)
      this.publish()
      this.delImg()
      this.getUserStatus()
    },
    typeChange: function () {
      var self = this
      $('.product_type li').on('click', function () {
        $(this).addClass('selected').siblings().removeClass('selected')
        var typeId = $(this).attr('type')
        $('#publish_type').val(typeId)
        if (typeId == 1) {
          $('#getCatsbox').show()
          $('#get2Catsbox').hide()
          self.getCatData()
        }
        if (typeId == 2) {
          $('#getCatsbox').hide()
          $('#get2Catsbox').show()
          self.getCat2Data()
        }
        if (typeId == 3) {
          $('#getCatsbox').hide()
          $('#get2Catsbox').hide()
          $('div.pricebox').hide()
        }else {
          $('div.pricebox').show()
        }
      })
    },
    getCat2Data: function () {
      var param = {type: 2}
      var arrs = []
      $.ajax({
        url: API_URL + GET_CATEGORYS_URL,
        type: 'get',
        dataType: 'jsonp',
        data: param,
        success: function (data) {
          // 分类拼接
          var datas = data.result
          var json = {}
          for (var i = 0;i < datas.length;i++) {
            json = {title: datas[i].name,value: datas[i].id}
            arrs.push(json)
          }
          $('#get2Cats').select({
            title: '选择分类',
            items: arrs,
            onChange: function (d) {
              $('#type_categoryId').val(d.values)
              $('#get2Cats p').html(d.titles)
            }
          })
        }
      })
    },
    getCatData: function () {
      var param = {type: 1}
      var arrs = []
      $.ajax({
        url: API_URL + GET_CATEGORYS_URL,
        type: 'get',
        dataType: 'jsonp',
        data: param,
        success: function (data) {
          // 分类拼接
          var datas = data.result
          var json = {}
          for (var i = 0;i < datas.length;i++) {
            json = {title: datas[i].name,value: datas[i].id}
            arrs.push(json)
          }
          $('#getCats').select({
            title: '选择分类',
            items: arrs,
            onChange: function (d) {
              $('#type_categoryId').val(d.values)
              $('#getCats p').html(d.titles)
            }
          })
        }
      })
    },
    uploadImg: function () {
      var f2 = document.querySelector('#addimgurls')
      var idsList = JSON.parse($('#idList').val() || '[]')

      f2.onchange = function (e) {
        var files = e.target.files
        var len = files.length
        for (var i = 0;i < len;i++) {
          lrz(this.files[i], {width: 750}).then(function (rst) {
            var params = {
              type: 2,
              file: rst.base64,
              name: rst.origin.name,
              fileLength: rst.base64.length
            }
            $.ajax({
              type: 'POST',
              url: API_URL + IMG_UPLOAD,
              data: params,
              dataType: 'json',
              beforeSend: function (XMLHttpRequest) {
                // showLoader()
              },
              success: function (data) {
                if (data.ok == true) {
                  $('#imgs').append('<li data-id=' + data.result.id + ' class="weui_uploader_file weui_uploader_status" style="background-image:url(' + data.result.smallUrl + ')"><div class="weui_uploader_status_content"><i class="icon icon-img-del"></i></div></li>')
                  var len = $('#imgs li').length
                  $('#imgsCount').html(len + '/4')
                  if (len == 4) {
                    $('#filed').hide()
                    return
                  }
                  if (len > 4) {
                    $.toptips('图片数量不能超过4张！', 'info')
                    return
                  }else {
                    $('#filed').show()
                  }
                  idsList.push(data.result.id)
                  $('#imageIds').val(JSON.stringify(idsList))
                }
              },
              complete: function (XMLHttpRequest, textStatus) {
                // hideLoader()
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.toptips('上传失败')
              }
            })
            return rst
          })
            .catch(function (err) {
              $.toptips(err)
            })
        }
      }
    },
    delImg: function () {
      $('#imgs').delegate('.icon-img-del', 'click', function () {
        var delimg = $(this).closest('li')
        var delId = $(this).closest('li').data('id')
        $.confirm('您确定删除吗？', '确认删除？', function () {
          var idsList = JSON.parse($('#imageIds').val() || '[]')
          idsList.remove(delId); // 从数组中删除项
          $('#imageIds').val(JSON.stringify(idsList))
          delimg.remove()
          var len = $('#imgs li').length
          $('#imgsCount').html(len + '/4')
          if (len < 4) {
            $('#filed').show()
          }
        }, function () {
          $.toast('取消操作', 'cancel')
        })
      })
    },
    verifySubmit: function () {
      var messages = $('#messages').val()
      var uploadImgs = $('#imageIds').val()
      var typeCategoryId = $('#type_categoryId').val()
      var price = $('#price').val()
      var typeId = $('ul.product_type li.selected').attr('type')
      if (typeId == 3) {
        if (uploadImgs == '') {
          $.toptips('请添加图片！', 'info')
          return false
        }
        if (messages == '') {
          $.toptips('请填写信息！', 'info')
          return false
        }
      }else {
        if (uploadImgs == '') {
          $.toptips('请添加图片！', 'info')
          return false
        }
        if (typeCategoryId == '') {
          $.toptips('请选择类目！', 'info')
          return false
        }
        if (messages == '') {
          $.toptips('请填写信息！', 'info')
          return false
        }
        if (price == '') {
          $.toptips('请填写价格！', 'info')
          return false
        }
      }
      return true
    },
    getUserStatus: function () {
      var self = this
      $.ajax({
        url: API_URL + GET_USER_INFO,
        type: 'post',
        dataType: 'jsonp',
        data: {id: self.userId},
        success: function (data) {
          if (data.ok == true) {
            var datas = data.result
            if (datas.idVerifyStatus != 1) {
              $.modal({
                title: '您的账号未认证，请认证后再发布。',
                buttons: [
                  { text: '知道了', onClick: function () {
                      window.location.href = 'index.html'
                  } },
                  { text: '去认证', className: 'default',onClick: function () {
                      window.location.href = 'set.html'
                  }}
                ]
              })
            }
            if (datas.status == -1) {
              $.modal({
                title: '您的账号已被停用！',
                buttons: [
                  { text: '知道了', onClick: function () {
                      window.location.href = 'index.html'
                  } },
                  { text: '申诉', className: 'default',onClick: function () {
                      window.location.href = 'appeals.html'
                  }}
                ]
              })
            }
            if (datas.status == 0) {
              $.modal({
                title: '您的账号已被冻结！！',
                buttons: [
                  { text: '知道了', onClick: function () {
                      window.location.href = 'index.html'
                  } },
                  { text: '申诉', className: 'default',onClick: function () {
                      window.location.href = 'appeals.html'
                  }}
                ]
              })
            }
          }
        }
      })
    },
    publish: function () {
      var self = this
      var $form = $('#formPublish')
      $form.form()
      $('#btn-publish').on('click', function () {
        var typeId = $('ul.product_type li.selected').attr('type')
        if (typeId == 1) {
          $.fn.cookie('publish_type', '1')
        }
        if (typeId == 2) {
          $.fn.cookie('publish_type', '2')
        }
        if (typeId == 3) {
          $.fn.cookie('publish_type', '3')
        }
        var params = {}
        if (typeId == 3) {
          $('#type_categoryId').removeAttr('required')
          $('#price').removeAttr('required')
          $('#imageIds').removeAttr('required')
          params = {
            userId: self.userId,
            message: $('#messages').val(),
            imageId: JSON.parse($('#imageIds').val() || '[]')
          }
          $form.validate(function (error) {
            if (error) {
              $.toptips(error.msg, 'info')
            }else {
              $.ajax({
                url: API_URL + PUBLISH_FEEDBACKS_URL,
                type: 'post',
                dataType: 'jsonp',
                data: params,
                beforeSend: function () {
                  $('#btn-publish').addClass('disabled')
                },
                success: function (data) {
                  if (data.ok == true) {
                    $.toast('发布成功!')
                    setTimeout(function () {
                      window.location.href = 'my_products_list.html'
                    }, 2000)
                  }
                },
                complete: function () {
                  $('#btn-publish').removeClass('disabled')
                },
                error: function (data) {
                  $.toptips(data.msg, 'info')
                }
              })
            }
          })
        }else {
          params = {
            userId: self.userId,
            desc: $('#messages').val(),
            imageId: JSON.parse($('#imageIds').val() || '[]'),
            type: $('#publish_type').val(),
            categoryId: $('#type_categoryId').val(),
            price: $('#price').val()
          }
          // $('#imageIds').attr('required',false)
          $form.validate(function (error) {
            if (error) {
              $.toptips(error.msg, 'info')
            }else {
              $.ajax({
                url: API_URL + PUBLISH_URL,
                type: 'post',
                dataType: 'jsonp',
                data: params,
                beforeSend: function () {
                  $('#btn-publish').addClass('disabled')
                },
                success: function (data) {
                  if (data.ok == true) {
                    $.toast('发布成功!')
                    setTimeout(function () {
                      window.location.href = 'my_products_list.html'
                    }, 2000)
                  }
                },
                complete: function () {
                  $('#btn-publish').removeClass('disabled')
                },
                error: function (data) {
                  $.toptips(data.msg, 'info')
                }
              })
            }
          })
        }
      })
    }
  }
  $(function () {
    publish.init()
  })
})(Zepto)
